package com.ai.spring.common.exception;

import com.ai.spring.common.enums.ExceptionEnum;
import com.ai.spring.common.util.ResponseResult;
import com.ai.spring.common.util.ResponseResultUtil;
import com.ai.spring.common.util.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * TODO
 *
 * @author 石头
 * @Date 2019/10/31
 * @Version 1.0
 **/
@Slf4j
@RestControllerAdvice
public class RestControllerExceptionHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult<String> validException(MethodArgumentNotValidException exception){
        // 打印堆栈信息
        log.error("validException:{}", ThrowableUtil.getStackTrace(exception));

        if (exception.getBindingResult()!=null && !CollectionUtils.isEmpty(exception.getBindingResult().getAllErrors())){
            return ResponseResultUtil.ofError(ExceptionEnum.PARAM_BIND_ERROR.getCode(),exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        }
        return ResponseResultUtil.ofError(ExceptionEnum.PARAM_BIND_ERROR.getCode(),exception.getMessage());
    }
    @ExceptionHandler(BindException.class)
    public ResponseResult<String> bindException(BindException exception){
        // 打印堆栈信息
        log.error("BindException:{}",ThrowableUtil.getStackTrace(exception));
        if (!CollectionUtils.isEmpty(exception.getAllErrors())){
            return ResponseResultUtil.ofError(ExceptionEnum.PARAM_BIND_ERROR.getCode(),exception.getAllErrors().get(0).getDefaultMessage());
        }

        return ResponseResultUtil.ofError(ExceptionEnum.PARAM_BIND_ERROR);
    }

    @ExceptionHandler(WebException.class)
    public ResponseResult<String> webException(WebException exception){
        // 打印堆栈信息
        log.error("WebException:{}", ThrowableUtil.getStackTrace(exception));

        return ResponseResultUtil.ofError(exception.getCode(),exception.getMessage());
    }
    @ExceptionHandler(FileTypeMultipartException.class)
    public ResponseResult<String> webFileTypeException(FileTypeMultipartException exception){
        // 打印堆栈信息
        log.error("webFileTypeException:{}", ThrowableUtil.getStackTrace(exception));

        return ResponseResultUtil.ofError(exception.getCode(),exception.getMessage());
    }
}
